import * as step from '@flow-step/step-toolkit'
import * as sinon from 'sinon';
import { expect } from 'chai'
import proxyquire from 'proxyquire'
import path from 'path'


describe('setDependentFiles and copyDependency', () => {
    let sandbox: sinon.SinonSandbox;
    let callStub: sinon.SinonStub;
    let debugStub: sinon.SinonStub;
    let fsStub: {
        existsSync: sinon.SinonStub;
        chmodSync: sinon.SinonStub;
        unlinkSync: sinon.SinonStub;
        copyFileSync: sinon.SinonStub;
    }

    beforeEach(() => {
        sandbox = sinon.createSandbox();
        callStub = sandbox.stub(step.exec, 'call').resolves(0);
        debugStub = sandbox.stub(step, 'debug').resolves();
        fsStub = {
            existsSync: sandbox.stub().returns(false),
            chmodSync: sandbox.stub(),
            unlinkSync: sandbox.stub(),
            copyFileSync: sandbox.stub(),
        };
    });

    afterEach(() => {
        sandbox.restore();
    });

    it('should copy dependent files and set permissions', async () => {
        const targetDir = '/root/plugin';

        const setDependentFilesProxy = proxyquire('../src/utils', {
            fs: fsStub,
        }).setDependentFiles;

        const currentDir = path.join(__dirname,'..','src');

        await setDependentFilesProxy(targetDir);
        expect(fsStub.copyFileSync.calledThrice).to.be.true
        expect(debugStub.calledWith('set permission for diff to 755')).to.be.true
        expect(debugStub.calledWith('set permission for builder to 755')).to.be.true
        expect(debugStub.calledWith(`js-codescan.tar was extracted to /root/plugin`)).to.be.true
        expect(debugStub.calledWith(`copy ${path.join(currentDir,'diff')} to /root/plugin/diff`)).to.be.true
        expect(debugStub.calledWith(`copy ${path.join(currentDir,'report-template.html')} to /root/plugin/report-template.html`)).to.be.true
    });

    it('should throw an error if extraction fails', async () => {
        const targetDir = '/root/plugin';

        const setDependentFilesProxy = proxyquire('../src/utils', {
            fs: fsStub,
        }).setDependentFiles;

        callStub.resolves(1)

        try {
            await setDependentFilesProxy(targetDir);
        }catch (e:any){
            expect(e.message).to.equal(`failed to extract js-codescan.tar to ${targetDir}, exitCode: 1`)
        }
    });
});
